//
//  WeatherRequest.m
//  SmartLife
//
//  Created by Lawrence on 15/10/9.
//  Copyright © 2015年 Lawrence. All rights reserved.
//

#import "WeatherRequest.h"
@implementation WeatherRequest
static NSString *weatherUrl=@"http://www.weather.com.cn/data/cityinfo/%@.html";
+(Weather *)initWithCityCode:(NSString *)code{
    WeatherRequest *weather=[[WeatherRequest alloc] init];
    return [weather GetCityWeatherWithCityCode:code];
}
-(Weather *)GetCityWeatherWithCityCode:(NSString *) code{
   //url链接请求
   NSString *url=[NSString stringWithFormat:weatherUrl,code];
   NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.cachePolicy=NSURLRequestReturnCacheDataElseLoad;
   NSHTTPURLResponse *urlResponse=nil;
   NSError *error=nil;
   NSData *recervedData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
   NSDictionary *dict=[self handlerJSONData:recervedData];
   if (dict!=nil) {
       NSDictionary *dictCityInfo=[dict objectForKey:@"weatherinfo"];
       Weather *weather=[[Weather alloc] initWeather:dictCityInfo];
       return weather;
   }
    return nil;
}
#pragma mark 解析josn数据
-(NSDictionary *)handlerJSONData:(NSData *) data{
    if (data!=nil) {
        NSError *error;
        //解析josn 数据
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        return dict;
    }
    return nil;
}
@end
